<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="审批状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
                <el-option v-for="dict in approval_record_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="applyTime" style="width: 308px">
              <el-date-picker
                v-model="createTimeRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:admCarDriveRecord:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate(any)" v-hasPermi="['system:admCarDriveRecord:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:admCarDriveRecord:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:admCarDriveRecord:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="admCarDriveRecordList" @selection-change="handleSelectionChange" style="width: 100%">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <!-- 车牌号 -->
        <el-table-column label="车牌号" align="center">
          <template #default="scope">
            <span>{{ scope.row.car?.carNumber || '未知车牌' }}</span>
          </template>
        </el-table-column>
        <!-- 总费用 -->
        <el-table-column label="总费用(元)" align="center">
          <template #default="scope">
            <span>{{ scope.row.totalAmount || 0 }}</span>
          </template>
        </el-table-column>
        <!-- 创建时间 -->
        <el-table-column label="创建时间" align="center" width="180">
          <template #default="scope">
            <span>{{ scope.row.createTimeSec || '-' }}</span>
          </template>
        </el-table-column>
        <!-- 审批状态 -->
        <el-table-column label="审批状态" align="center">
          <template #default="scope">
            <dict-tag :options="approval_record_status" :value="scope.row.records?.[0]?.status" />
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 车辆申请查询对话框 -->
    <el-dialog
      v-model="dialog.visible"
      title="车辆行驶记录申请"
      width="1000px"
      append-to-body
      :before-close="cancel"
    >
      <!-- 可选固定信息 -->
      <el-form ref="filterFormRef" :model="form" label-width="100px" label-position="left"
        style="padding: 20px 0 20px 24px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="记录人" prop="recordName">
              <el-input v-model="form.recordName" placeholder="请输入记录人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="记录部门" prop="deptName">
              <el-tree-select
                v-model="form.deptName"
                :data="deptTree"
                placeholder="请选择部门"
                :props="{ label: 'label', value: 'id', children: 'children' }"
                check-strictly
                filterable
                :default-expand-all="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆选择">
              <el-select
                v-model="form.carId"
                placeholder="请选择车辆"
                filterable
                @change="onCarChange"
              >
                <el-option
                  v-for="car in carList"
                  :key="car.id"
                  :label="`${car.model} (${car.carNumber})`"
                  :value="car.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="时间范围" prop="dateRange">
              <el-date-picker
                v-model="form.dateRange"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
                @change="onDateChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 查询结果列表 -->
      <div class="application-list" style="margin-top: 20px;">
        <el-divider></el-divider>
        <el-card
          v-for="(item, index) in filteredApplications"
          :key="item.id"
          class="application-card"
          shadow="hover"
        >
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <span>申请 {{ index + 1 }}</span>
          </div>
          <el-form :model="item" :rules="generateItemRules(item)" :ref="el => setItemFormRef(el as ElFormInstance, item.id)" label-width="106px" label-position="left" style="padding: 20px 0 20px 20px;">
            <el-row :gutter="20" style="margin-top: 10px;">
              <el-col :span="8">
                <el-form-item label="用车人">
                  <el-input v-model="item.useName" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="出发地">
                  <el-input v-model="item.departurePlace" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="目的地">
                  <el-input v-model="item.destination" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用车时间">
                  <el-input v-model="item.useTime" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="返回时间">
                  <el-input v-model="item.backTime" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="用车事由">
                  <el-input v-model="item.useReason" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="随行人员">
                  <el-input v-model="item.entourageId" placeholder="请输入起始里程" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="驾驶人员">
                  <el-input v-model="item.driverName" placeholder="请输入起始里程" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="车牌号">
                  <el-input v-model="item.carName" placeholder="请输入起始里程" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="车辆性质">
                  <el-input
                    :model-value="carTypeMap[item.carType] || '未知'"
                    placeholder="车辆性质"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="记录时间" prop="recordTime">
                  <el-date-picker clearable
                    v-model="item.recordTime"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择记录时间"
                    style="width: 100%;">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目名称" prop="projectName">
                  <el-tree-select
                    v-model="item.projectName"
                    :data="projectTree"
                    placeholder="请选择项目名称"
                    :props="{ label: 'contractName', value: 'id', children: 'children' }"
                    filterable
                    clearable
                    style="width: 100%"
                    @change="id => handleProjectChange(id, item)"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="起始里程">
                  <el-input v-model="item.startMileage" placeholder="请输入起始里程" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="终止里程" prop="endMileage">
                  <el-input v-model="item.endMileage" placeholder="请输入终止里程" @input="handleMileageChange(item)" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="里程数" prop="mileageNumber">
                  <el-input v-model="item.mileageNumber" placeholder="请输入里程数" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="过路费(元)" prop="toll">
                  <el-input v-model="item.toll" placeholder="请输入过路费" @input="computeAmountAll(item)"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="油费(元)" prop="fuelCost">
                  <el-input v-model="item.fuelCost" placeholder="请输入油费" @input="computeAmountAll(item)"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="油耗(L/100km)" prop="oilConsumption">
                  <el-input v-model="item.oilConsumption" placeholder="请输入油耗" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="油价(元/L)" prop="oilPrice">
                  <el-input v-model="item.oilPrice" placeholder="请输入油价(元/L)" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="油费补贴(元)" prop="postageSubsidy">
                  <el-input v-model="item.postageSubsidy" placeholder="请输入油费补贴" @input="computeAmountAll(item)"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="停车费(元)" prop="parkFree">
                  <el-input v-model="item.parkFree" placeholder="请输入停车费" @input="computeAmountAll(item)"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="租赁费(元)" prop="rentalFree" >
                  <el-input v-model="item.rentalFree" placeholder="请输入租赁费" @input="computeAmountAll(item)"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="维修费(元)" prop="maintenanceCost">
                  <el-input v-model="item.maintenanceCost" placeholder="请输入维修费" @input="computeAmountAll(item)"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="其它费用(元)" prop="otherExpenses">
                  <el-input v-model="item.otherExpenses" placeholder="请输入其它费用" @input="computeAmountAll(item)"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="总费用(元)" prop="amountAll">
                  <el-input v-model="item.amountAll" placeholder="请输入总费用" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="附件上传" prop="attachmentName">
                  <el-input v-model="item.attachmentName" readonly placeholder="请点击附件上传" @click="handleAttachmentUpload(item,2)"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="item.remark" placeholder="请输入备注" type="textarea" :rows="3"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
        <div v-if="filteredApplications.length === 0" class="no-application">暂无申请数据</div>
      </div>

      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" :loading="loading" @click="submitAll">提交</el-button>
      </template>
    </el-dialog>
   

     <!-- 导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        v-model:file-list="uploadRefFileList"
        accept=".jpg,.png,.jpeg,.gif"
        :headers="upload.headers"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-remove="handleFileRemove"
        :auto-upload="false"
        :multiple="true"
        drag
        list-type="picture"
      >
        <el-icon class="el-icon--upload">
          <UploadFilled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <span>仅允许导入.jpg, .png, .jepg, .PNG, .gif图片格式。</span>
            <!-- <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="handleImportTemplate"
              >下载模板</el-link
            > -->
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="upload.isUploading" @click="submitFileForm">确 定</el-button>
          <el-button @click="cancelUpload">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AdmCarDriveRecord" lang="ts">
import { getProContract } from '@/api/project/init/contract';
import { listAdmCarDriveRecord, getAdmCarDriveRecord, delAdmCarDriveRecord, addAdmCarDriveRecord, updateAdmCarDriveRecord, batchAddRecords, batchUpdateRecords } from '@/api/general/administration/car/drive';
import { AdmCarDriveRecordVO, AdmCarDriveRecordQuery, AdmCarDriveRecordForm } from '@/api/general/administration/car/drive/types';
import { uploadAttachment, deleteUploadFile, queryApplyListByUser, queryAllByUser, getCarUseRecords } from '@/api/general/administration/car/apply';
import { queryCanInfo } from '@/api/general/administration/car/store';
import { AdmCarStoreDto } from '@/api/general/administration/car/store/types';
import { AdmCarApplyVO, AdmCarApplyQuery } from '@/api/general/administration/car/apply/types';
import type { DeptTreeNode } from '@/api/general/administration/seal/types';
import { getDeptTree } from '@/api/general/administration/seal';
import { useUserStore } from '@/store/modules/user';
import { globalHeaders } from '@/utils/request';
import { UploadQuery } from '@/api/general/administration/car/upload/types';
import { listProContract } from '@/api/project/init/contract';
import { getProInfo, pageListProInfo } from '@/api/project/init/proInfo';
import { ItemTreeNode } from '@/api/project/init/contract/types';
import { getUser } from '@/api/system/user/index'
import { Row } from 'element-plus/es/components/table-v2/src/components/index.mjs';
import { any } from 'vue-types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 全局配置
const BASE_URL = import.meta.env.VITE_APP_BASE_API || 'http://localhost:8080';
const admCarDriveRecordList = ref<AdmCarDriveRecordVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 用户信息
const userStore = useUserStore();

// 初始化申请表
const applyList = ref<AdmCarApplyVO[]>([]);
const carList = ref<any[]>([]);

// 初始化项目下拉框
const projectTree = ref<ItemTreeNode[]>([]);

// 部门树初始化
const deptTree = ref<DeptTreeNode[]>([]);
// 记录上一次打开的行记录
let lastDialogRecordKey: string | number | null = null

// 引入数据字典
const { car_type_options, approval_record_status } = toRefs<any>(proxy?.useDict('car_type_options', 'approval_record_status'));

// 过滤后的申请表
const filteredApplications = ref<any[]>([]);

// 导入相关
const uploadRef = ref<any>();
// 已上传文件，用于回显和 form.attachment
const uploadedFiles = ref<any[]>([]);
// 当前待上传文件列表
const uploadRefFileList = ref<any[]>([]);
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 上传的类型
  type: undefined,
  // 设置上传的请求头部
  headers: globalHeaders()
});

const currentItem = ref<any>(null) // 当前操作的 item

const itemFormRef = ref(new Map<string, ElFormInstance | null>())
function setItemFormRef(el: ElFormInstance | null, id: number | string) {
  const key = String(id)
  if (el) {
    itemFormRef.value.set(key, el)
  } else {
    itemFormRef.value.delete(key)
  }
}

// 时间选择器查询参数初始化
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const createTimeRange = ref<[DateModelType, DateModelType]>(['', '']);

const carTypeMap = {
  0: '私车',
  1: '公车',
  2: '租车'
};

const queryFormRef = ref<ElFormInstance>();
const admCarDriveRecordFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 本地时间格式化函数
const formatLocalDate = (date = new Date()) => {
  const padZero = num => String(num).padStart(2, '0');
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`;
};

/**
 * 生成32位UUID
 * @returns string 32位UUID
 */
function generateUUID32(): string {
  // 生成标准 UUID v4，然后去掉 "-"
  return 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.replace(/[x]/g, () =>
    ((Math.random() * 16) | 0).toString(16)
  );
}


const initFormData: AdmCarDriveRecordForm = {
  id: undefined,
  recordId: userStore.userId,
  recordName: userStore.name,
  deptId: userStore.deptId,
  deptName: userStore.deptName,
  recordTime: formatLocalDate(),
  carApplyId: undefined,
  applyVos: [] as AdmCarApplyVO[],
  // 申请表数据字段暂存
  startMileage: undefined, 
  carType: undefined,
  useId: userStore.userId,
  endMileage: undefined,
  mileageNumber: undefined,
  toll: undefined,
  fuelCost: undefined,
  oilConsumption: undefined,
  oilPrice: undefined,
  postageSubsidy: undefined,
  parkFree: undefined,
  rentalFree: undefined,
  maintenanceCost: undefined,
  otherExpenses: undefined,
  amountAll: undefined,
  attachmentId: undefined,
  attachmentName: undefined,
  remark: undefined,
  number: undefined,
  status: undefined,
  dateRange: undefined,
  carId: undefined,
  selected: undefined,
}
const data = reactive<PageData<AdmCarDriveRecordForm, AdmCarDriveRecordQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    carApplyId: undefined,
    endMileage: undefined,
    mileageNumber: undefined,
    toll: undefined,
    fuelCost: undefined,
    oilConsumption: undefined,
    oilPrice: undefined,
    postageSubsidy: undefined,
    parkFree: undefined,
    rentalFree: undefined,
    maintenanceCost: undefined,
    otherExpenses: undefined,
    amountAll: undefined,
    attachmentId: undefined,
    number: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {}
});

// 动态图书表单校验规则（除了备注，其他都必填）
// 为每个 item 生成独立 rules
const generateItemRules  = (item) => ({
  endMileage: [
    { required: true, message: '请输入终止里程', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        const start = Number(item.startMileage)
        const end = Number(value)
        if (!isNaN(start) && !isNaN(end) && end < start) {
          callback(new Error('终止里程不能小于起始里程'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  mileageNumber: [
    { required: true, pattern: /^(\d+)(\.\d{1,2})?$/, message: '请输入数字，小数点后最多两位', trigger: 'blur' }
  ],
  toll: [
    { required: false, pattern: /^(\d+)(\.\d{1,2})?$/, message: '请输入数字，小数点后最多两位', trigger: 'blur' }
  ],
  fuelCost: [
    { required: false, pattern: /^(\d+)(\.\d{1,2})?$/, message: '请输入数字，小数点后最多两位', trigger: 'blur' }
  ],
  oilConsumption: [
    { required: false, pattern: /^(\d+)(\.\d{1,2})?$/, message: '请输入数字，小数点后最多两位', trigger: 'blur' }
  ],
  oilPrice: [
    { required: false, pattern: /^(\d+)(\.\d{1,2})?$/, message: '请输入数字，小数点后最多两位', trigger: 'blur' }
  ],
  postageSubsidy: [
    { required: false, pattern: /^(\d+)(\.\d{1,2})?$/, message: '请输入数字，小数点后最多两位', trigger: 'blur' }
  ],
  parkFree: [
    { required: false, pattern: /^(\d+)(\.\d{1,2})?$/, message: '请输入数字，小数点后最多两位', trigger: 'blur' }
  ],
  rentalFree: [
    { required: false, pattern: /^(\d+)(\.\d{1,2})?$/, message: '请输入数字，小数点后最多两位', trigger: 'blur' }
  ],
  maintenanceCost: [
    { required: false, pattern: /^(\d+)(\.\d{1,2})?$/, message: '请输入数字，小数点后最多两位', trigger: 'blur' }
  ],
  otherExpenses: [
    { required: false, pattern: /^(\d+)(\.\d{1,2})?$/, message: '请输入数字，小数点后最多两位', trigger: 'blur' }
  ],
  amountAll: [
    { required: false, pattern: /^(\d+)(\.\d{1,2})?$/, message: '请输入数字，小数点后最多两位', trigger: 'blur' }
  ],
  attachmentName: [
    { required: true, message: '请上传附件', trigger: 'blur' }
  ]
})


const { queryParams, form, rules } = toRefs(data);

/** 查询车辆行驶记录列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    if (dateRange.value?.length === 2) {
      params.params = {
        ...params.params,
        bUseTime: dateRange.value[0]?.toString(),
        eUseTime: dateRange.value[1]?.toString()
      };
    }
    if (createTimeRange.value?.length === 2) {
      params.params = {
        ...params.params,
        beginTime: createTimeRange.value[0]?.toString(),
        endTime: createTimeRange.value[1]?.toString()
      };
    }
    const res = await listAdmCarDriveRecord(params);
    admCarDriveRecordList.value = res.rows;
    console.log('Fetched list:', admCarDriveRecordList.value);
    total.value = res.total;
  } catch (error) {
    console.error('获取列表失败:', error);
    proxy?.$modal.msgError('获取列表失败');
  } finally {
    loading.value = false;
  }
}

/** 取消按钮 */
const cancel = () => {
  // 重置表单
  reset();
  // 关闭弹窗
  dialog.visible = false;
  // 清空记录列表（可选，看需求是否保留）
  filteredApplications.value = [];
  // 清空上传组件状态
  uploadRefFileList.value = [];
  uploadRef.value?.clearFiles();
  upload.open = false;
  currentItem.value = null;
};

/** 删除按钮操作 */
const handleDelete = async (row?: AdmCarDriveRecordVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除车辆行驶记录编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delAdmCarDriveRecord(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 表单重置 */
const reset = () => {
  // 深拷贝，避免旧引用残留
  form.value = JSON.parse(JSON.stringify(initFormData));
  // 重置表单校验
  admCarDriveRecordFormRef.value?.resetFields();
  // 清空上传组件
  uploadRefFileList.value = [];
  uploadRef.value?.clearFiles();
  // 清空当前附件对象
  currentItem.value = null;
}


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  createTimeRange.value = ['', ''];
  queryFormRef.value?.resetFields();
    queryParams.value.params = {
    bUseTime: undefined,
    eUseTime: undefined,
    beginTime: undefined,
    endTime: undefined
  };
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: AdmCarDriveRecordVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加车辆行驶记录"; 
  // 同步到 currentItem
  currentItem.value = { ...form.value, _uploadedFiles: [] };
  console.log('新增表单 currentItem:', currentItem.value);
}

const handleUpdate = async (row: any) => {
  reset(); // 重置表单
  currentItem.value = row;
  console.log("当前操作的行驶记录", row);

  // car 回显
  const carObj = row.car || {};
  Object.assign(form.value, {
    recordName: row.records?.[0]?.recordName || '',
    deptName: row.records?.[0]?.deptName || '',
    carId: carObj.id || '',
    carName: carObj.carName || carObj.name || '',
    dateRange: [row.minUseTime, row.maxBackTime],
  });

  // 异步回显申请列表 & 记录，包括附件
  filteredApplications.value = await Promise.all(
    row.applyList?.map(async (apply) => {
      const record = row.records?.find(r => r.carApplyId === apply.id) || {};
      // 获取项目名称
      let projectName = null;
      if (record.projectId) {
        const project = await getProInfo(record.projectId); // 假设返回 { data: { proName, proNumber } }
        projectName = project?.data ? `${project.data.proName} (${project.data.proNumber})` : null;
      }
      // 获取附件
      let fileList: any[] = [];
      if (record.number && record.recordId) {
        const query: UploadQuery = { number: record.number, uploadId: record.recordId };
        console.log("附件查询参数:", query);
        const response = await queryAllByUser(query);
        console.log("接口返回附件数据:", response.data);
        fileList = (response.data || []).map(f => ({
          id: f.id,
          name: f.name,
          url: getFileUrl(f.url) || '',
          fullUrl: getFileUrl(f.url),
          raw: null,
          status: 'success'
        }));
      }
       // 同步附件名称给 input
      const attachmentName = fileList.map(f => f.name).join(',');
      return {
        ...apply,
        ...record,
        recordTime: record.recordTime ? record.recordTime.split('T')[0] : null,
        projectName,
        fileList,                // 每条申请记录独立 file-list
        _uploadedFiles: fileList, // 原有逻辑兼容
        attachmentName            // 用于 input 回显
      };
    }) || []
  );

  console.log("回显的申请列表", filteredApplications.value);

  dialog.visible = true;
  dialog.title = '修改车辆行驶记录';
};


/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/admCarDriveRecord/export', {
    ...queryParams.value
  }, `admCarDriveRecord_${new Date().getTime()}.xlsx`)
}

// 对话框打开时滚动到顶部
const handleDialogOpen = async () => {
  await nextTick(); // 确保 DOM 渲染完成
  // 使用 document.querySelector 精准获取 Teleport 后的 el-dialog__body
  const scrollBody = document.querySelector<HTMLElement>('.seal-dialog .el-dialog__body');
  if (scrollBody) {
    scrollBody.scrollTop = 0; // 滚动到顶部
  } else {
    console.warn('未找到 el-dialog__body');
  }
};

// 查询申请表中本次申请的数据
const getApplyData = async () => { 
  const param: AdmCarApplyQuery = {
    useId: userStore.userId,
    pageNum: 1,
    pageSize: 100
  };
  const res = await queryApplyListByUser(param);
  applyList.value = res.data;
  console.log("申请表数据", applyList.value);
}



// 处理里程变化，传入当前 item
const handleMileageChange = (item) => {
  computeMileage(item)
}

// 计算里程数
const computeMileage = (item) => {
  const start = Number(item.startMileage)
  const end = Number(item.endMileage)
  if (isNaN(start) || isNaN(end)) {
    item.mileageNumber = undefined
    return
  }
  item.mileageNumber = end >= start ? end - start : undefined
}


/**
 * 文件上传中处理
 */
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};


/**
 * 提交上传文件
 */
const submitFileForm = async () => {
  if (!currentItem.value) return;

  const files = uploadRefFileList.value.map(f => f.raw).filter(Boolean);
  if (!files.length) {
    ElMessage.warning('请先选择文件！');
    return;
  }

  upload.isUploading = true;
  try {
    await uploadAttachment(files, userStore.userId, currentItem.value.number, upload.type);
    await loadAttachments(currentItem.value); // 加载上传后的附件

    // 文件已经回显在 currentItem.value._uploadedFiles 中
    currentItem.value.attachmentId = currentItem.value._uploadedFiles.map(f => f.id).join(',');
    currentItem.value.attachmentName = currentItem.value._uploadedFiles.map(f => f.name).join(',');

    ElMessage.success('上传成功');
    uploadRefFileList.value = [];
    uploadRef.value?.clearFiles();
    upload.open = false;
  } catch (err) {
    console.error(err);
    ElMessage.error('上传失败，请重试');
  } finally {
    upload.isUploading = false;
  }
};



/**
 * 打开附件上传弹窗
 */
const handleAttachmentUpload = async (item: any, type: number) => {
  console.log("当前项:", item);
  currentItem.value = item;
  upload.type = type;
  upload.title = '附件信息上传';
  upload.open = true;

  // 回显已有附件
  uploadRefFileList.value = [...(item._uploadedFiles || [])];
  uploadRef.value?.clearFiles();

  if (item.number) {
    await loadAttachments(item);  // 加载已有附件
  }
};


 // 页面初始化或表单加载完成后调用
const loadAttachments = async (item: any) => {
  if (!item.number || !userStore.userId) return;
  try {
    const query: UploadQuery = { number: item.number, uploadId: userStore.userId };
    const response = await queryAllByUser(query);
    console.log("附件查询结果:", response.data);
    const existingFiles = (response.data || []).map(f => ({
      id: f.id,
      name: f.name,
      url: getFileUrl(f.url) || '',
      fullUrl: getFileUrl(f.url),
      raw: null,
      status: 'success'
    }));
    // 挂载到当前 item
    item._uploadedFiles = existingFiles;
    // 上传组件绑定
    uploadRefFileList.value = [...existingFiles];
    // 同步到表单字段
    item.attachmentId = existingFiles.map(f => f.id).join(',');
    item.attachmentName = existingFiles.map(f => f.name).join(',');
    console.log('更新后的 item:', item);
  } catch (err) {
    console.error('附件加载失败', err);
    ElMessage.error('附件加载失败');
  }
}




// 取消上传
const cancelUpload = () => {
  upload.open = false;
  uploadRefFileList.value = [];
  uploadRef.value?.clearFiles();
};

// 获取完整 URL
const getFileUrl = (url: string) => {
  if (!url) return '';
  // 已经是完整路径就直接返回
  if (url.startsWith('http') || url.startsWith('file://')) return url;
  // 去掉前面的 '/upload'，然后拼接
  const fileName = url.substring(url.lastIndexOf('/') + 1); 
  return `${BASE_URL}upload/${fileName}`;
};

/**
 * 删除单个文件
 * @param file 当前删除的文件对象
 * @param index 文件在 file-list 中的索引
 */
const handleFileRemove = async (file: any) => {
  if (!currentItem.value) return;

  try {
    if (file.id) await deleteUploadFile(file.id);
    ElMessage.success(`${file.name} 已删除`);
    await loadAttachments(currentItem.value); // 刷新附件列表
  } catch (err) {
    console.error(err);
    ElMessage.error(`删除文件 ${file.name} 失败`);
  }
};


const computeAmountAll = (item) => {
  // 提取需要计算的费用字段
  const {
    toll,
    fuelCost,
    postageSubsidy,
    parkFree,
    rentalFree,
    maintenanceCost,
    otherExpenses,
    carType
  } = item
  // 转成数值（空值按 0 处理）
  const num = (val) => (val != null ? Number(val) : 0);  // null 或 undefined 都按 0 处理
  // 计算每项费用
  const tollNum = num(toll)
  const fuelNum = num(fuelCost)
  const parkNum = num(parkFree)
  const rentalNum = carType == 2 ? num(rentalFree) : 0
  const maintenanceNum = num(maintenanceCost)
  const otherNum = num(otherExpenses)
  const subsidyNum = num(postageSubsidy)
  // 费用项总和
  const total = tollNum + fuelNum + parkNum + rentalNum + maintenanceNum + otherNum - subsidyNum
  // 保留两位小数
  item.amountAll = total !== 0 ? Number(total.toFixed(2)) : 0;

}


const getCarLabel = (carId) => {
  const car = applyList.value.find(item => item.id === carId)
  if (!car) return ''
  return `${car.carName} (出发地：${car.departurePlace} 到 目的地：${car.destination}) (起始里程数：${car.startMileage})`
}

// 车辆选择变化
const onCarChange = (carId: number) => {
  console.log("选择的车辆 ID:", carId);
  form.value.carId = carId;
  loadRecords();
};

// 时间范围变化
const onDateChange = () => {
  console.log("选择的时间范围:", form.value.dateRange);
  loadRecords();
};

// 调用接口
const loadRecords = async () => {
  let startTime: string | undefined
  let endTime: string | undefined
  if (form.value.dateRange && form.value.dateRange.length === 2) {
    [startTime, endTime] = form.value.dateRange
  }
  const userId = userStore.userId
  try {
    const { data } = await getCarUseRecords(form.value.carId, startTime, endTime, userId)
    const records = data || []
    // 使用 for...of + await 遍历每条记录，保证异步处理顺序
    for (const item of records) {
      // 1️⃣ 设置默认记录时间
      if (!item.recordTime) {
        item.recordTime = formatLocalDate()
      }
      // 2️⃣ 获取随行人员名称
      if (item.entourageId) {
        try {
          const ids = item.entourageId.split(',').map(id => id.trim()).filter(Boolean)
          if (ids.length) {
            const results = await Promise.all(ids.map(id => getUser(id)))
            item.entourageName = results
              .map(r => r?.data?.user?.userName)
              .filter(Boolean)
              .join(',')
          } else {
            item.entourageName = ''
          }
        } catch (err) {
          console.error('获取随行人失败:', err)
          item.entourageName = ''
        }
      } else {
        item.entourageName = ''
      }
      item.number = generateUUID32()
    }
    filteredApplications.value = records
    console.log('查询结果:', filteredApplications.value)
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询车辆使用记录失败')
  }
}

/** 批量新增 */
const submitAll = async () => {
  if (!filteredApplications.value.length) {
    ElMessage.warning('请至少添加一条记录后再提交')
    return
  }

  if (!form.value) {
    ElMessage.error('表单未就绪，请稍后重试')
    return
  }

  let valid = true
  for (const item of filteredApplications.value) {
    const formRef = itemFormRef.value.get(String(item.id))
    if (formRef) {
      const ok = await formRef.validate().catch(() => false)
      if (!ok) valid = false
    } else {
      valid = false
    }
    item.carId = form.value.carId
  }
  if (!valid) return

  // 根据 recordId 判断新增或修改
  const newRecords = filteredApplications.value
    .filter(item => !item.recordId)
    .map(({ id, ...rest }) => ({
      ...rest,
      carApplyId: id
    }))

  const updateRecords = filteredApplications.value
    .filter(item => item.recordId)
    .map(({ id, ...rest }) => ({
      ...rest,
      id: id
    }))

  try {
    if (newRecords.length) {
      console.log('新增记录:', newRecords);
      await batchAddRecords({
        ...form.value,
        records: newRecords
      })
      ElMessage.success('新增记录成功')
    }

    if (updateRecords.length) {
      await batchUpdateRecords({
        ...form.value,
        records: updateRecords
      })
      ElMessage.success('修改记录成功')
    }

    dialog.visible = false
    await getList()
    filteredApplications.value = []
  } catch (err) {
    console.error(err)
    ElMessage.error('操作失败，请重试')
  }
}




// 获取部门树
const fetchDeptTree = async () => {
  try {
    const res = await getDeptTree();
    const processNode = (node: any) => {
      if (node.children && node.children.length > 0) {
        // 有子节点 → 禁用，但允许展开
        node.disabled = true;
        node.children.forEach(processNode); // 递归处理子节点
      } else {
        // 叶子节点 → 可选
        node.disabled = false;
      }
    };
    if (Array.isArray(res.data)) {
      res.data.forEach(processNode);
    }
    deptTree.value = res.data;
  } catch (error) {
    console.error('获取部门树失败:', error);
    proxy?.$modal.msgError('获取部门树失败');
  }
};

// 获取车辆全部信息
const getCarList = async () => {
  try {
    const param: AdmCarStoreDto = {
      isLend: '0',
      status: 1,
      // 其他字段根据需要添加
    };
    const response = await queryCanInfo(param);
    carList.value = response.data || [];
  } catch (error) {
    console.error('获取车辆列表失败:', error);
    proxy?.$modal.msgError('获取车辆列表失败');
  }
};

const handleProjectChange = (selectedId: number, item: any) => {
  const findProject = (nodes: any[]): any => {
    for (const node of nodes) {
      if (node.id === selectedId) return node;
      if (node.children) {
        const child = findProject(node.children);
        if (child) return child;
      }
    }
    return null;
  };
  const project = findProject(projectTree.value);
  if (project) {
    item.projectId = project.id;
    item.projectName = project.contractName;
  } else {
    item.projectId = null;
    item.projectName = '';
  }
};

// 获取全部子项目（树级赋值，父节点不可选择）
const fetchProjectList = async () => {
  try {
    // 1. 获取合同列表
    const contractRes = await listProContract();
    const contracts = (contractRes?.rows || []).filter(
      (c: any) => c.contractStatus == 3
    );
    // 2. 获取项目列表
    const projectRes = await pageListProInfo();
    const projects = projectRes?.rows || [];
    // 3. 构建树结构
    const treeData = contracts.map((contract: any) => {
      const children = projects
        .filter((p: any) => p.contractId === contract.id)
        .map((p: any) => ({
          id: p.id,
          contractName: `${p.proName} (${p.proNumber})`, // 拼接 proName 和 proNumber
          contractId: contract.id
        }));

      return {
        id: contract.id,
        contractName: contract.contractName, // 父节点显示合同名
        disabled: true,
        children
      };
    });

    projectTree.value = treeData;
    console.log("项目树数据:", projectTree.value);
  } catch (error) {
    console.error("获取项目列表失败:", error);
    proxy?.$modal.msgError("获取项目列表失败");
  }
};

onMounted(() => {
  getList();
  getApplyData();
  fetchDeptTree();
  getCarList();
  fetchProjectList();
});
</script>
<style scoped>
.seal-dialog :deep(.el-dialog__header) {
  text-align: center;
}

/* 合同对话框中的用户选择器样式 */
.user-selector-container {
  width: 100%;
}

.user-selector-container .selected-users {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 8px;
  min-height: 20px;
}

/* 对话框样式优化 */
:deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto !important;
  display: block; /* 确保是块级元素 */
}
</style>